package proxyServer;

import java.util.Vector;

public class ProxyHttpReply
{
	private final int defaulttimeout  = 2000;
	private int       m_contentLength = 0;
	
	public int getContentLength()
	{
		return m_contentLength;
	}
	
	private String m_connection = null;
	
	public String getConnectionString()
	{
		return m_connection;
	}
	
	private String m_strKeepalive;
	
	public int getTimeout()
	{
		try
		{
			return Integer.parseInt(m_strKeepalive);
		}
		catch (Exception e)
		{
			// TODO: handle exception
			return defaulttimeout;
		}
	}
	
	public boolean isSetupTimeout()
	{
		if (m_strKeepalive == null) return false;
		return true;
	}
	
	public boolean isCloseConenction()
	{
		if (m_connection == null) return true;
		if (m_connection.compareTo("close") == 0)
		{
			return true;
		}
		return false;
	}
	
	private boolean m_hasheader = false;
	
	public boolean getHasHeader()
	{
		return m_hasheader;
	}
	
	Vector<String> arrStr = new Vector<String>();
	
	public void addHeader(String str)
	{
		arrStr.add(str);
	}
	
	public boolean parse(byte[] arrbyte)
	{
		String streamstr = new String(arrbyte);
		
		int start = streamstr.indexOf("Content-Length: ") + 16;
		int end = streamstr.indexOf('\n', start);
		
		String len = streamstr.substring(start, end - 1);
		
		try
		{
			m_contentLength = Integer.parseInt(len);
		}
		catch (Exception ex)
		{
			return false;
		}
		start = streamstr.indexOf("Connection: ");
		if (start != -1)
		{
			start += 12;
			end = streamstr.indexOf('\n', start);
			m_connection = streamstr.substring(start, end - 1);
			start = streamstr.indexOf("Keep-alive: ");
			if (start != -1)
			{
				start += 12;
				end = streamstr.indexOf('\n', start);
				m_strKeepalive = streamstr.substring(start, end - 1);
			}
		} else
		{
			m_connection = null;
		}
		m_hasheader = true;
		return true;
	}
	
	public boolean parse()
	{
		for (String str : arrStr)
		{
			if (str.indexOf("Content-Length: ") != -1)
			{
				try
				{
					m_contentLength = Integer.parseInt(str.substring(16));
				}
				catch (Exception ex)
				{
					return false;
				}
			}
		}
		return true;
	}
}
